// 学生照片数据库工具类
export interface StudentPhotoData {
  id: string
  taskId: string
  studentId: string
  thumbnail: string
  fullImage: string
  timestamp: number
  teacherID: string
  fileName: string
  fileSize: string
  description: string
  status: 'pending' | 'graded' | 'corrected'
}

class StudentPhotosStorage {
  private db: IDBDatabase | null = null
  private readonly DB_NAME = 'student-photos-db'
  private readonly STORE_NAME = 'student-photos'
  private readonly VERSION = 1

  async init() {
    if (this.db) return

    return new Promise<void>((resolve, reject) => {
      const request = indexedDB.open(this.DB_NAME, this.VERSION)

      request.onerror = (event) => {
        console.error('Failed to open student photos database:', event)
        reject(new Error('Failed to open student photos database'))
      }

      request.onsuccess = (event) => {
        this.db = (event.target as IDBOpenDBRequest).result
        resolve()
      }

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result
        
        if (!db.objectStoreNames.contains(this.STORE_NAME)) {
          const store = db.createObjectStore(this.STORE_NAME, { keyPath: 'id' })
          store.createIndex('taskId', 'taskId', { unique: false })
          store.createIndex('studentId', 'studentId', { unique: false })
          store.createIndex('timestamp', 'timestamp', { unique: false })
          store.createIndex('status', 'status', { unique: false })
        }
      }
    })
  }

  async saveStudentPhoto(photo: StudentPhotoData): Promise<void> {
    if (!this.db) await this.init()

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.STORE_NAME], 'readwrite')
      const store = transaction.objectStore(this.STORE_NAME)
      const request = store.put(photo)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(new Error('Failed to save student photo'))
    })
  }

  async saveStudentPhotos(photos: StudentPhotoData[]): Promise<void> {
    if (!this.db) await this.init()

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.STORE_NAME], 'readwrite')
      const store = transaction.objectStore(this.STORE_NAME)
      
      let completed = 0
      let error: any = null

      photos.forEach(photo => {
        const request = store.put(photo)
        
        request.onsuccess = () => {
          completed++
          if (completed === photos.length && !error) {
            resolve()
          }
        }
        
        request.onerror = (e) => {
          error = e
          reject(new Error('Failed to save student photos'))
        }
      })

      transaction.onerror = () => reject(new Error('Transaction failed'))
    })
  }

  async getStudentPhotosByTask(taskId: string, studentId: string): Promise<StudentPhotoData[]> {
    if (!this.db) await this.init()

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.STORE_NAME], 'readonly')
      const store = transaction.objectStore(this.STORE_NAME)
      const request = store.getAll()

      request.onsuccess = () => {
        const photos = request.result.filter(
          (photo: StudentPhotoData) => photo.taskId === taskId && photo.studentId === studentId
        )
        resolve(photos)
      }

      request.onerror = () => reject(new Error('Failed to get student photos'))
    })
  }

  async getAllStudentPhotos(): Promise<StudentPhotoData[]> {
    if (!this.db) await this.init()

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.STORE_NAME], 'readonly')
      const store = transaction.objectStore(this.STORE_NAME)
      const request = store.getAll()

      request.onsuccess = () => resolve(request.result)
      request.onerror = () => reject(new Error('Failed to get all student photos'))
    })
  }

  async deleteStudentPhoto(photoId: string): Promise<void> {
    if (!this.db) await this.init()

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.STORE_NAME], 'readwrite')
      const store = transaction.objectStore(this.STORE_NAME)
      const request = store.delete(photoId)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(new Error('Failed to delete student photo'))
    })
  }

  async clearStudentPhotos(): Promise<void> {
    if (!this.db) await this.init()

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.STORE_NAME], 'readwrite')
      const store = transaction.objectStore(this.STORE_NAME)
      const request = store.clear()

      request.onsuccess = () => resolve()
      request.onerror = () => reject(new Error('Failed to clear student photos'))
    })
  }
}

export const studentPhotosStorage = new StudentPhotosStorage()